<template>
  <div></div>
</template>
<script>
import Utils from '@/common/pakjUtils';
import { Dialog } from 'mand-mobile';
import http from '@/common/http';
import Config from '@/common/config';
const STATE_STRING = 'JigoutixianWxauth';
export default {
  name: 'jigoutixian',
  data() {
    return {
      userId: undefined,
      companyId: undefined,
      code: undefined,
      state: undefined
    };
  },
  created() {
    if (!Utils.isWeixinBroswer()) {
      console.error('必须在微信浏览器内使用');
      Dialog.alert({
        title: '错误',
        content: '必须在微信客户端内使用此功能'
      });
      return;
    }
    let query = Utils.parseQueryString(null);
    if (query.userid) {
      this.userId = query.userid;
    }
    if (query.cmpid) {
      this.companyId = query.cmpid;
    }
    if (query.code) {
      this.code = query.code;
    }
    if (query.state) {
      this.state = query.state;
    }
    if (this.state === STATE_STRING) {
      if (this.code && this.userId && this.companyId) {
        http
          .post('/pakj/wexin/financeBindWx ', {
            userid: this.userId,
            cmpid: this.companyId,
            code: this.code
          })
          .then(res => {
            if (res.data.code === '000000') {
              Dialog.succeed({
                title: '授权成功',
                onConfirm: () => {
                  if (window.wx) {
                    window.wx.closeWindow();
                  }
                }
              });
            } else {
              Dialog.alert({
                title: res.data.code,
                content: res.data.msg
              });
            }
          })
          .catch(reason => {
            Dialog.alert({
              title: '错误',
              content: reason.message
            });
          });
      } else {
        Dialog.alert({
          title: '错误',
          content: '授权错误'
        });
      }
      return;
    }
    let param = {
      appid: Config.appid,
      redirect_uri: encodeURIComponent(window.location.href),
      response_type: 'code',
      scope: 'snsapi_userinfo',
      state: STATE_STRING
    };
    let arr = [];
    for (var key in param) {
      let str = key + '=' + param[key];
      arr.push(str);
    }
    let paramStr = arr.join('&');
    window.location.href = Config.wxauth + '?' + paramStr + '#wechat_redirect';
  }
};
</script>